<template>
  <div
    ref="ratioImg"
    class="ratio-img"
    :style="imgStyle">
    <img
      v-if="img_src"
      @error="handleImgError"
      :src="img_src" class="img">
    <i
      v-else
      class="el-icon-picture"
      :style="iconStyle"></i>
  </div>
</template>

<script>
  /**
   * @Author: lifuzhao
   * @Date: 2019-05-15
   * @Project: eabax
   */
  export default {
    name: 'ratio-img',
    props: {
      useWidth: {
        type: Boolean,
        default: false
      },
      height: {
        type: Number,
        default: 36
      },
      ratio: {
        type: Number,
        default: 9/16
      },
      src: {
        type: String,
        default: ''
      },
      borderRadius: {
        type: String,
        default: '4px'
      }
    },
    data(){
      return {
        error: false,
        parent_height: null
      }
    },
    computed: {
      imgStyle(){
        let height = this.parent_height || this.height,
          borderRadius = this.borderRadius
        let ratio = this.ratio,
          width = height / ratio
        return {
          width: width + 'px',
          height: height + 'px',
          'border-radius': borderRadius
        }
      },
      iconStyle(){
        let height = this.parent_height || this.height
        return {
          fontSize: (height * 0.75) + 'px'
        }
      },
      img_src(){
        let error = this.error
        return error ? '' : this.src
      }
    },
    mounted(){
      let height = this.height,
        useWidth = this.useWidth,
        ratio = this.ratio,
        ratioImg = this.$refs.ratioImg,
        parent = ratioImg.parentNode
      let style = window.getComputedStyle(parent)
      if(useWidth){
        let width = style.width.replace('px', '')
        height = width * ratio
      }else if(!height){
        height = style.height.replace('px', '')
      }
      if(height){
        this.parent_height = height
      }
    },
    methods: {
      handleImgError(){
        this.error = true
      }
    }
  }
</script>

<style lang="less">
  .ratio-img{
    display: inline-flex;
    justify-content: center;
    align-items: center;
    background-color: #eee;
    border-radius: 4px;
    overflow: hidden;
    .img{
      width: 100%;
      height: 100%;
    }
    .el-icon-picture{
      color: #c4c4c4;
    }
  }
</style>
